<?php
/**
 * @title 常用的一些函数
 * @author Leruge
 * @email lereuge@163.com
 * @qq 305530751
 */
use think\exception\HttpResponseException;

if (!function_exists('check_captcha')) {
    /**
     * @title 校验验证码
     * @desc 不通过则抛出http响应异常
     *
     * @param string|int $phone 手机
     * @param string|int $code 验证码
     * @param string|int $msg 不通过提示信息
     */
    function check_captcha(string|int $phone, string|int $code, string|int $msg = '验证码不正确')
    {
        if (cache('code' . $phone) != $code && $code != '888888') {
            $res = [
                'code' => $code,
                'msg' => $msg,
                'data' => null,
                'time' => date('Y-m-d H:i:s') 
            ];
            throw new HttpResponseException(json($res));
        }
        cache('code' . $phone, null);
    }
}

if (!function_exists('format_time')) {
    /**
     * @title 格式化时间
     *
     * @param int|null $time 整型时间戳
     * @param int $type 1是Y-m-d H:i:s；2是Y-m-d H:i；3是Y-m-d；4是聊天时间
     *
     * @return string|null 时间
     */
    function format_time(?int $time, int $type = 1): ?string
    {
        if (empty($time)) {
            return null;
        }
        $formatTime = null;
        if ($type === 1) {
            $formatTime = date('Y-m-d H:i:s', $time);
        }

        if ($type === 2) {
            $formatTime = date('Y-m-d H:i', $time);
        }

        if ($type === 3) {
            $formatTime = date('Y-m-d', $time);
        }

        if ($type === 4) {
            $today = mktime(0, 0, 0, (int)date('m'), (int)date('d') + 1, (int)date('Y'));
            $validTime = abs($today - $time);
            $oneDay = 3600 * 24;
            if ($validTime < $oneDay) {
                $formatTime = date('H:i', $time) ?: null;
            } elseif ($validTime >= $oneDay && $validTime < $oneDay * 2) {
                $formatTime = date('H:i', $time) ? '昨天 ' . date('H:i', $time) : null;
            } elseif ($validTime >= $oneDay * 2) {
                $formatTime = date('Y-m-d', $time) ?: null;
            }
        }
        return $formatTime;
    }
}

if (!function_exists('generate_nickname')) {
    /**
     * @title 生成昵称
     *
     * @return string 昵称
     */
    function generate_nickname(): string
    {
        try {
            return mb_strtoupper(bin2hex(random_bytes(3)));
        } catch (Throwable) {
            return '这个人很懒';
        }
    }
}

if (!function_exists('handle_get_pic')) {
    /**
     * @title 获取图片
     * @desc 依赖extra配置文件中的app_url
     *
     * @param string|null $pics 图片
     * @param int $type 1处理单张图片；2是处理多张；3是多张取一张
     *
     * @return string|null 图片
     */
    function handle_get_pic(?string $pics, int $type = 1): ?string
    {
        $pic = $pics;
        if (empty($pics)) {
            return null;
        }
        if ($type === 1) {
            if (substr($pics, 0, 1) === '/') {
                $pic = config('extra.app_url') . trim($pics, '/');
            }
        }
        if ($type === 2) {
            $picArray = array_filter(explode(',', $pics));
            $newPicArray = [];
            foreach ($picArray as $v) {
                if (substr($v, 0, 1) === '/') {
                    $newPicArray[] = config('extra.app_url') . trim($v, '/');
                } else {
                    $newPicArray[] = $v;
                }
            }
            $pic = implode(',', $newPicArray);
        }
        if ($type === 3) {
            $picArray = array_filter(explode(',', $pics));
            $pic = $picArray[0] ?? null;
            $pic = handle_get_pic($pic);
        }
        return $pic;
    }
}

if (!function_exists('handle_set_pic')) {
    /**
     * @title 设置图片
     *
     * @param string|null $pics 图片
     * @param integer $type 1是单张；2是多张
     *
     * @return string|null 图片
     */
    function handle_set_pic(?string $pics, int $type = 1): ?string
    {
        if (empty($pics)) {
            return null;
        }
        $pic = null;
        if ($type === 1) {
            if (stripos($pics, config('extra.app_url')) === 0) {
                $pic = '/' . trim(str_ireplace(config('extra.app_url'), '/', $pics), '/');
            } else {
                $pic = $pics;
            }
        }
        if ($type === 2) {
            $picArray = array_filter(explode(',', $pics));
            foreach ($picArray as $k => $v) {
                if (stripos($v, config('extra.app_url')) === 0) {
                    $handlePics = '/' . trim(str_ireplace(config('extra.app_url'), '/', $v), '/');
                } else {
                    $handlePics = $v;
                }
                $picArray[$k] = $handlePics;
            }
            $pic = implode(',', $picArray);
        }
        return $pic;
    }
}

if (!function_exists('handle_set_content')) {
    /**
     * @title 处理内容
     *
     * @param string|null $content 内容
     *
     * @return string 内容
     */
    function handle_set_content(?string $content): string
    {
        return str_ireplace('src="' . config('extra.app_url'), 'src="/', $content);
    }
}

if (!function_exists('handle_get_content')) {
    /**
     * @title 获取内容
     *
     * @param string|null $content 内容
     *
     * @return string 内容
     */
    function handle_get_content(?string $content): string
    {
        return str_ireplace('src="/', 'src="' . config('extra.app_url'), $content);
    }
}

if (!function_exists('handle_get_num')) {
    /**
     * @title 获取数字
     *
     * @param int|null $num 数字
     *
     * @return int|string 数量
     */
    function handle_get_num(?int $num): int|string
    {
        $num = empty($num) ? 0 : $num;
        if ($num > 9999) {
            $num = round($num / 10000, 1) . 'w';
        }
        return $num;
    }
}

if (!function_exists('generate_room_num')) {
    /**
     * @title 生成聊天房间号
     *
     * @param int $fromId 发送者ID
     * @param int $toId 接受者ID
     *
     * @return string 房间号
     */
    function generate_room_num(int $fromId, int $toId): string
    {
        if ($fromId === $toId) {
            $res = [
                'code' => 0,
                'msg' => '房间无效',
                'data' => null,
                'time' => date('Y-m-d H:i:s')
            ];
            throw new HttpResponseException(json($res));
        }
        return $fromId > $toId ? $toId . '-' . $fromId : $fromId . '-' . $toId;
    }
}

if (!function_exists('result')) {
    /**
     * @title 封装json响应
     *
     * @param mixed $data 数据
     * @param integer $code 1是成功；0是失败；其它码看说明
     * @param mixed $msg 提示消息
     *
     * @throws HttpResponseException
     */
    function result(mixed $data = null, int $code = 1, mixed $msg = '操作成功')
    {
        $res = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => date('Y-m-d H:i:s')
        ];
        throw new HttpResponseException(json($res));
    }
}
